<template>
    <div id="container">
        <mt-header class="top" :title="botui?'医疗助手': '客服'+msg.username" style="background:#fff;border-bottom:1px solid #edeff0;height:6vh;color:#101010">  
            <mt-button icon="back" slot="left" @click="btn1()" style="display:inline-block;text-indent:5px;"></mt-button>
        </mt-header>
        
        <ul :class="[!faceShow?'noShow':'isShow','content']"  ref="charView" @click="()=>{faceShow = false}">   
            
            <li v-for="(item, index) in messageList" :key="index">
                <img v-if="!item.myself" src="../../assets/images/doctor.jpg" class="imgleft mx-2">
                <img v-if="item.myself" :src="user.haedPic" class="imgright mx-2">
                <div style="height: 50px; width: 100%; position: relative;"  @click.prevent="play_mp3(item.src,index)">
                  <!-- <div v-if="!item.myself" class="mx-3 text-grey fs-sm">{{botui?'小医': '客服'+msg.username}}</div>
                  <div v-if="item.myself" class="d-flex jc-end text-grey fs-sm">{{user.username}}</div> -->
                  <div class="pr-2" style="position: absolute; right: 41%; z-index: 80; line-height: 38px" v-if="item.src">
                    <div class="el-icon-video-play fs-xxxxl" v-if="!play&&currentIndex != index">
                    </div>
                    <div class="el-icon-loading fs-xxxxl" v-if="currentIndex === index">
                    </div>
                  </div>
                  <div class="span1" v-html="item.message" contenteditable="false" :class="'span'+(item.myself?'right':'left')">
                        
                          
                               
                  </div>   
                </div> 
            </li>
            
            
        </ul>
        <!-- 中间黑框 录音状态 -->
        <div class="blackBoxSpeak" v-if="recording">
          <div class="el-icon-microphone fs-xxxl text-white" style="font-size: 5.5rem;margin: 2rem 3.6rem"></div>
          <p class="blackBoxSpeakConent">手指移动，取消发送</p>
        </div>
        
        

        <div class="footer_wrap">
            <div class="px-2 py-2">
                
                <!-- <div v-if="faceShow" @click="" class="iconfont icon-xinaixin fs-xxl"></div> -->
            </div>
            
            <div class="footer">
                   <div class="audio" @click="showRecorder">
                       <div v-if="!showrecorder" class="el-icon-microphone fs-xxxl" style="font-size: 2rem"></div>
                       <!-- <van-icon v-if="!showrecorder" name="play-circle-o" size="2rem" /> -->
                       <div v-if="showrecorder" class="iconfont icon-dingdan fs-xxxl"></div>
                   </div>
                   <span @touchstart="gotouchstart" @touchmove="gotouchmove" @touchend="gotouchend" v-if="showrecorder" class="recorder" @click="recorder">{{text}}</span>
                   <input v-if="!showrecorder" id="text" type="text" v-model.trim="inputValue" @keyup.enter='chat' placeholder="" ref="shareTextArea"> 
                   
                
                <div @click="changShow" :class="['iconfont',faceShow?'icon-dingdan':'icon-xinaixin','fs-xxxl','emojo']"></div>
                
                    <span id="btn" @click="btn2()">发送</span>
                
                

            </div>
            <!-- //表情区域 -->
            <emotion @emotion="handleEmotion" :height="200" v-if="faceShow"></emotion>
        </div>

        

        
    </div>
</template>
<script type="text/javascript" src="http://apps.bdimg.com/libs/jquery/1.10.0/jquery.min.js"></script>
<script>

  import Stomp from 'stompjs'
  import Vue from 'vue'
  import { MQTT_SERVICE, MQTT_USERNAME, MQTT_PASSWORD } from '../../func/sysconstant.js'
    //引入表情包
    import Emotion from '@/components/public/emotion'
    //引入语音录制
    import Recorderx, { ENCODE_TYPE } from "recorderx";
    const rc = new Recorderx();
    var timeOutEvent=0;//定时器  
    var bMark = true
    export default{
         
        name:'Kefu',
        data() {
            return {
             //输入的内容,事先约定好的
            inputValue: '',
            //聊天的数组内容
            messageList: [
            {
                message: '您好，我是您的医疗助手小优，有什么可以帮助您的？',
                myself: false
            },
            {
                message: '如有复杂情况，请输入【小优，转在线医生】 我们安排专业医生帮您在线诊断',
                myself: false
            },

            ],
            scrollHeight: 0,
            user:{},
            //表情
            faceShow: false,
            content: '',
            comment: '',
            // 语音
            showrecorder: false,
            src:'',
            text: '按下 录音',
            recording: false,
            client: Stomp.client(MQTT_SERVICE),
            botui: true,
            msg: {

            },
            
            //
            audio:null,
            
            
            duration:null,
            play: false,
            playing: false,
            currentIndex: null,
            url: 'user/wulaiBot/getDoctorAnswer.do',
            userIndex: false,//用户是否在线
            doctorIndex: false
        }
    },//点击回车时候发送信息
    
    components: {
      Emotion,
    },
    watch:{
        //监听信息列表变化 变化就把页面到底
        messageList(){
          this.scrollToBottom();
        },
        inputValue(){
          this.userIndex = true
        }
          
      
    },
    created(){
        this.user = this.$store.getters.userInfo; 
    },
    methods: {
        recorder(){},
        gotouchstart(){
           this.recording = true
           this.text = '松开结束'
           clearTimeout(timeOutEvent);//清除定时器
           timeOutEvent = 0;
           timeOutEvent = setTimeout(()=>{
                //执行长按要执行的内容，
                this.handleBtnClick()
             },300);//这里设置定时
        },
        //手释放，如果在500毫秒内就释放，则取消长按事件，此时可以执行onclick应该执行的事件
        gotouchend(){
          this.text = '按下 录音'
          this.recording = false
          // this.send_voice();
          clearTimeout(timeOutEvent);
          if(timeOutEvent!=0){
          //这里写要执行的内容（尤如onclick事件）
          this.send_voice();
          this.cancel_mp3();
          this.cancel()
          this.messageList.push({
            message: `
                    <div class="d-flex ai-center pl-3 px-2 ml-2">
                      
                      <div>${this.format(this.duration)}</div>
                    </div>
            `,
                    //这个是判断当前是否是自己输入的内容,自己的是true,机器人的是false
                    myself: true,
                    src: this.src,
                    time: this.duration
                  })
          
          console.log('录音完成')
              }
          },
//如果手指有移动，则取消所有事件，此时说明用户只是要移动而不是长按 
        gotouchmove(){
             this.recording = false
             this.cancel_mp3()
             this.cancel()
             clearTimeout(timeOutEvent);//清除定时器
             timeOutEvent = 0;
             
         },
        //语音开始
         //录制语音
         handleBtnClick: function () {
          let that = this
          // that.news_img = !that.news_img
          rc.start()
          .then(() => {
            // that.news_img = !that.news_img
            console.log("start recording");
        })
          .catch(error => {
            alert('获取麦克风失败 当前浏览器不支持')
            console.log("Recording failed.", error);
        });
        },
        //暂停语音
        cancel_mp3: function() {
          rc.pause();

        },
        //取消语音
        cancel: function() {
          rc.clear();

        },
        // 播放语音
        play_mp3:function(src,index){
          
          if (src) {
            this.currentIndex = index;
            
            this.audio=new Audio()
            this.audio.src=src
            
            //获取时长
            this.audio.addEventListener('canplaythrough',()=>{
              this.duration=this.format(this.audio.duration)
            })
            
            if(bMark){
                bMark = false
                this.audio.play()
            }else{
                this.audio.pause();
                return
                
            }
            //播放中
            
            this.audio.onplay=()=>{
                console.log(1)
                
              }

              //播放完
            this.audio.onended=()=>{
                this.audio.pause()
                 console.log('播放完了');
                 this.play = false;
                 bMark = true;
                 this.currentIndex = null
            }

            
            
            
          }
        // document.getElementById('audio').src = URL.createObjectURL(wav);
        },
        //发送语音
        send_voice: function () {
         
         var wav = rc.getRecord({
          encodeTo: ENCODE_TYPE.WAV,
          compressible: true
        });
         console.log(wav)
         this.duration = wav.size/20480
         this.src = URL.createObjectURL(wav);
         // var uuid = this.uuid;
         /*if (this.chatList != "") {
            var end_time = this.chatList[this.chatList.length - 1].addtime;
        }*/
        var formData = new FormData();
        formData.append('file',wav);
        // formData.append('topic_id',uuid);
        // formData.append('last_time',end_time);
        formData.append('type',4);
        formData.append("file", wav,Date.parse(new Date())+".wav");
        let headers = {headers: {"Content-Type": "multipart/form-data"}}
        console.log(1)
        axios.defaults.withCredentials=true
        this.$http.post(this.url,formData,headers).then(res => {
          if (res.data.answer) {
            this.messageList.push({

              message: res.data.answer,
                    //这个是判断当前是否是自己输入的内容,自己的是true,机器人的是false
                    myself: false
                  })
          }
                    rc.clear();
                })
        .catch(err => {
          console.log(err);
        });


         this.doctorIndex = false;
         //如果医生不在 转回 机器人
         if (this.botui === false) {
          setTimeout(()=>{
            if(this.doctorIndex === false && this.botui === false){
             this.url = 'user/wulaiBot/getDoctorAnswer.do'
             this.botui = true;
             this.messageList.push({
              message: '医生正忙哦 ~ 小优来帮您解决问题',
              myself: false
            });
           }
         },60000)


        }

        },

        //语音结束
        showRecorder(){
            this.showrecorder = !this.showrecorder
            if (this.showrecorder === true) {
              this.faceShow = false
            }
        },
        // 是否显示表情框
        changShow(){
            this.faceShow = !this.faceShow
            if (this.faceShow) {
               this.showrecorder = false
            }
        },
        scrollToBottom() {
         this.$nextTick(() => {
            var container =this.$refs.charView;

            container.scrollTop = container.scrollHeight;
        })},

         chat() {
            this.messageList.push({
                message: this.inputValue.replace(/\#[\u4E00-\u9FA5]{1,3}\;/gi, this.emotion),
                    //这个是判断当前是否是自己输入的内容,自己的是true,机器人的是false
                    myself: true
                })

                //每次发送信息之后机器人就要回复,所以添加完之后直接调用机器人的接口
                this.$http.post(this.url,{
                    question: this.inputValue
                }).then(res => {
                    
                    if (res.data.answer) {
                      this.messageList.push({
                        message: res.data.answer,
                        myself: false
                      });
                    }
                    this.$refs.charView.scrollTop=1000000;
                    this.scrollToBottom()

                })
                if (this.inputValue.indexOf('小优') != -1) {
                  this.url = 'user/wulaiBot/sendMessage.do'
                }
                //如果医生不在 转回 机器人
                this.doctorIndex = false;
                if (this.botui === false) {
                    setTimeout(()=>{
                      if(this.doctorIndex === false && this.botui === false){
                       this.url = 'user/wulaiBot/getDoctorAnswer.do'
                       this.botui = true;
                      this.messageList.push({
                        message: '医生正忙哦 ~ 小优来帮您解决问题',
                        myself: false
                      });
                      }
                    },60000)
                    
                  
                }
                this.inputValue=""
                
                
            },
            btn1(){
                this.$router.push('/home')
                //停止结束消息
                this.subscription.unsubscribe();
                this.client.disconnect(function() {
                  
                });
                this.client.connected = false
            },
            btn2(){
                
                this.messageList.push({

                    message: this.inputValue.replace(/\#[\u4E00-\u9FA5]{1,3}\;/gi, this.emotion),
                    //这个是判断当前是否是自己输入的内容,自己的是true,机器人的是false
                    myself: true
                })
                
                this.$http.post(this.url,{
                    question: this.inputValue,
                    
                }).then(res => {
                  
                    if (res.data.answer) {
                      this.messageList.push({
                        message: res.data.answer,
                        myself: false
                      });
                    }
                    

                })
                if (this.inputValue.indexOf('小优') != -1) {
                  this.url = 'user/wulaiBot/sendMessage.do'
                }
                //如果医生不在 转回 机器人
                this.doctorIndex === false;
                if (this.botui === false) {
                    setTimeout(()=>{
                      if(this.doctorIndex === false && this.botui === false){
                       this.url = 'user/wulaiBot/getDoctorAnswer.do'
                       this.botui = true;
                      this.messageList.push({
                        message: '医生正忙哦 ~ 小优来帮您解决问题',
                        myself: false
                      });
                      }
                    },60000)
                    
                  
                }
                this.inputValue=""
                
            },
            handleEmotion (i) {
              this.inputValue += i
          },
    // 将匹配结果替换表情图片
    emotion (res) {
      let word = res.replace(/\#|\;/gi,'')
      const list = ['微笑', '撇嘴', '色', '发呆', '得意', '流泪', '害羞', '闭嘴', '睡', '大哭', '尴尬', '发怒', '调皮', '呲牙', '惊讶', '难过', '酷', '冷汗', '抓狂', '吐', '偷笑', '可爱', '白眼', '傲慢', '饥饿', '困', '惊恐', '流汗', '憨笑', '大兵', '奋斗', '咒骂', '疑问', '嘘', '晕', '折磨', '衰', '骷髅', '敲打', '再见', '擦汗', '抠鼻', '鼓掌', '糗大了', '坏笑', '左哼哼', '右哼哼', '哈欠', '鄙视', '委屈', '快哭了', '阴险', '亲亲', '吓', '可怜', '菜刀', '西瓜', '啤酒', '篮球', '乒乓', '咖啡', '饭', '猪头', '玫瑰', '凋谢', '示爱', '爱心', '心碎', '蛋糕', '闪电', '炸弹', '刀', '足球', '瓢虫', '便便', '月亮', '太阳', '礼物', '拥抱', '强', '弱', '握手', '胜利', '抱拳', '勾引', '拳头', '差劲', '爱你', 'NO', 'OK', '爱情', '飞吻', '跳跳', '发抖', '怄火', '转圈', '磕头', '回头', '跳绳', '挥手', '激动', '街舞', '献吻', '左太极', '右太极']
      let index = list.indexOf(word)
      return `<img src="https://res.wx.qq.com/mpres/htmledition/images/icon/emotion/${index}.gif" align="middle">`   
  },
  //转人工服务
  //消息中间件
      onConnected: function (frame) {
        
        var topic = '/exchange/sendMessage'  
        // ---订阅频道
        this.subscription = this.client.subscribe(topic, this.responseCallback, this.onFailed) 
      },
      onFailed: function (frame) {
        
        console.log('Failed: ' + frame)
      },
      responseCallback: function (frame) {
        //可以调用send()来发送STOMP消息。  client会发送一个STOMP发送帧给/queue/test，这个帧包含一个设置了priority为9的header和内容为“Hello, STOMP”的body

        // client.send("/queue/test", {priority: 9}, "Hello, STOMP");
        // ---接收消息
        if (frame.body) {
          this.doctorIndex = true;
          this.botui = false;
          this.userIndex = false;
          this.msg = JSON.parse(frame.body)
          if (this.msg.username === this.user.username) {
            this.messageList.push({
              message: this.msg.answer,
                    //这个是判断当前是否是自己输入的内容,自己的是true,机器人的是false
                    myself: false
                  })
          }
          
        }
        if (this.inputValue === '') {
           if (this.botui === false) {
              setTimeout(()=> {
                if (this.userIndex === false && this.botui === false) {
                  this.url = 'user/wulaiBot/getDoctorAnswer.do'
                  this.botui = true;
                  this.messageList.push({
                    message: '由于您长时间没回答，在线医生已与你断开连接',
                    //这个是判断当前是否是自己输入的内容,自己的是true,机器人的是false
                    myself: false
                  })
                }
                
              },60000)
              
            
          }

        }else {

        }
        /*if (this.botui === false && !frame.body) {
            const inter =  setInterval(()=> {

            },) 
        }*/
      },
      connect() {
        // ---初始化mqtt客户端，并连接mqtt服务
        // var clientid = util.uuid()
         var headers = {
          'login': MQTT_USERNAME,
          'passcode': MQTT_PASSWORD,
          // 'client-id': clientid
        // additional header
          }
          this.client.connect(headers, this.onConnected, this.onFailed)   
      },
        format(s){
            var t='';
            if(s > -1){
                var min = Math.floor(s/60) % 60;
                var sec = s % 60;

                if(min < 10){t += "0";}
                t += min + "'";
                if(sec < 10){t += "0";}
                t += sec.toFixed(2);
            }
            t=t.replace('.','\"')
            return t;
        },



},
mounted() {
 this.box=this.$refs.charView;
 this.scrollToBottom();
 //初始化
 this.connect()
  
 }
        
}
</script>
<style lang="scss" scoped>


* {    
    margin: 0;
    padding: 0;
    list-style: none;
    font-family: '微软雅黑'
}
.top{
    width: 100%;
    position: fixed;
    top: 0;
    z-index: 99;
}
#container {
    width: 100vw;
    height: 100vh;
    background: #fafafa;
    position: relative;
    box-shadow: 20px 20px 55px #777;
}
.header {

    background: #000;
    height: 40px;
    color: #fff;
    line-height: 34px;
    font-size: 20px;
    padding: 0 10px;
}
.footer_wrap {
    width: 100vw;
    /*height: 4.2rem;*/

    position: fixed;
    bottom: 0;
    z-index: 99;

}
.footer {
    width: 100vw;
    height: 4.2rem;
    background-color: #edeff0;

    overflow: hidden;

}
.footer input {
    margin-top: 10px;
    width: 60vw;
    height: 40px;
    outline: none;
    font-size: 20px;
    text-indent: 10px;
    position: absolute;
    border-radius: 6px;
    margin-left: 10px;
    left: 8%;
}
.emojo {
    margin-top: 10px;
    width: 10vw;
    height: 40px;
    position: absolute;
    display: inline-block;
    right: 20%;
    text-align: center;
    line-height: 40px;
}
.footer #btn {
    margin-top: 10px;
    display: inline-block;
    width: 15vw;
    height: 40px;
    background: #ccc;
    font-weight: 900;
    line-height: 40px;
    cursor: pointer;
    text-align: center;
    position: absolute;
    right: 10px;
    border-radius: 6px;
}
.footer span:hover {
    color: #fff;
    background: #999;
}
#user_face_icon {
    display: inline-block;
    background: red;
    width: 60px;
    height: 60px;
    border-radius: 30px;
    position: absolute;
    bottom: 6px;
    left: 14px;
    cursor: pointer;
    overflow: hidden;
}
img {
    width: 50px;
    height: 50px;
}
.content {
    font-size: 20px;
    width: 100vw;
    height: 100vh;
    padding-top: 50px;
    
    overflow: auto;

}
.isShow {
  padding-bottom: 280px;
}
.noShow {
    padding-bottom: 80px;
}
.content li {
    margin-top: 10px;
    display: block;
    clear: both;
    overflow: hidden;
}
.imgleft {
    float: left;
}
.imgright {
    float: right;
}
.content li .spanleft{
    position: relative;
    
        max-width: 310px;
        min-height: 45px;
        background: #25a23b;
        border-radius: 5px;
        line-height: 50px;
        margin-left: 10px;
        word-break: break-word;
        
        padding: 10px;
        line-height: 18px;
        
}
.spanleft::before{
            content: "";
            display: block;
            position: absolute;
            width: 0;
            height: 0;
            border: 10px solid transparent;
            border-right-color: #ffff;
            top: 11px;
            left: -18px;


}

.spanright::before{
            content: "";
            display: block;
            position: absolute;
            width: 0;
            height: 0;
            border: 10px solid transparent;
            border-left-color: #7cfc00;
            top: 11px;
            right: -18px;


        }

.content li div .spanleft { 
    float: left;
    background: #fff;
    line-height: 1.4rem;
    display: flex;
    align-items: center;
}
.content li div .spanright { 
    float: right;
    // background: #7cfc00;
    // line-height: 1.4rem;
    // display: flex;
    // align-items: center;
    position: relative;
    
        max-width: 310px;
        min-height: 40px;
        background: #7cfc00;
        border-radius: 5px;
        // line-height: 50px;
        margin-right: 10px;
        word-break: break-word;
        padding: 10px;
        line-height: 1.4rem;
        align-items: center;
}
/*表情区域*/
.browBox {
 width: 100%;
 height: 200px;
 background: #e6e6e6;
 

 overflow: scroll;
 ul {
  display: flex;
  flex-wrap: wrap;
  padding: 10px;
  li {
  width: 14%;
  font-size: 26px;
  list-style: none;
  text-align: center;
  padding-bottom: 15px;
  color: #ffc32d;
  }
 }
 }

.audio {
    margin-top: 10px;
    width: 10vw;
    height: 40px;
    position: absolute;
    display: inline-block;
    left: 0%;
    text-align: center;
    line-height: 40px;
    display: flex;
    justify-content: center;
    align-items: center;
}
.recorder{
    margin-top: 10px;
    display: inline-block;
    width: 60vw;
    height: 40px;
    background: #ccc;
    font-weight: 900;
    line-height: 40px;
    cursor: pointer;
    text-align: center;
    position: absolute;
    left: 10%;
    border-radius: 6px;
}
//录音特效
.blackBoxSpeak {
            width: 176px;
            height: 176px;
            position: absolute;
            left: 0;
            right: 0;
            top: 0;
            bottom: 0;
            margin: auto;
            background: url("../../assets/images/weixin/ic_record@2x.png") no-repeat 28px 16px/65px 104px,
            url("../../assets/images/weixin/ic_record_ripple@2x-9.png") no-repeat 111.2px 32px/28.8px 88px;
            
            background: rgba(0, 0, 0, .7);
            
            border-radius: 12px;
        }
        
        .blackBoxSpeakConent {
            font: 14.4px '微软雅黑 Light';
            position: absolute;
            left: 0;
            right: 0;
            bottom: 12px;
            display: block;
            text-align: center;
            width: 90%;
            padding: 8px 0;
            margin: auto;
            color: #ffffff;
            font-weight: 200;
            border-radius: 4px;
        }
img {
  border-radius: 10px;
}


//播放动画
.middle{
        position: absolute;
        top:50%;
        left:50%;
        transform: translate(-50%,-50%);


      }
    .bar{
      width: 6px;
      height: 60px;
      background: white;
      display: inline-block;
      /*缩放开始位置*/
      transform-origin: bottom center; 
      animation: loading 1.5s ease-in-out infinite;
    }
    .bar1 {
      animation-delay: 0.1s;
    }
    .bar2 {
      animation-delay: 0.2s;
    }
    .bar3 {
      animation-delay: 0.3s;
    }
    .bar4 {
      animation-delay: 0.4s;
    }
    .bar5 {
      animation-delay: 0.5s;
    }
    .bar6 {
      animation-delay: 0.6s;
    }
    .bar7 {
      animation-delay: 0.7s;
    }
    .bar8 {
      animation-delay: 0.8s;
    }
    @keyframes loading {
      0%{
        
        transform: scaleY(0.1);
        background: #fff;
      }
      50%{
               transform: scaleY(1);
         background: #2ecc71;
      }
      100%{
               transform: scaleY(0.1);
         background: transparent;
    }
  }


</style>
